<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\model\system\SystemAdmin;
use app\common\controller\AdminController;
use app\services\system\SystemAdminService;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Env;

/**
 * Class Login
 * @package app\admin\controller
 */
class Login extends AdminController
{

    /**
     * 初始化方法
     */
    public function initialize()
    {
        parent::initialize();
        $action = $this->request->action();
        if (!empty(session('admin')) && !in_array($action, ['out'])) {
            $adminModuleName = config('app.admin_alias_name');
            $this->success('已登录，无需再次登录', [], __url("@{$adminModuleName}"));
        }
    }

    /**
     * 用户登录
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $captcha = Env::get('etong.captcha', 1);
        $this->assign('captcha', $captcha);
        $this->assign('demo', $this->isDemo);
        return $this->fetch('index');
    }

    public function login()
    {
        $captcha = Env::get('etong.captcha', 1);
        $post    = $this->request->post();
        $rule    = [
            'username|用户名'      => 'require',
            'password|密码'       => 'require',
            'keep_login|是否保持登录' => 'require',
        ];

        $captcha == 1 && $rule['captcha|验证码'] = 'require|captcha';

        $this->validate($post, $rule);
        /** @var SystemAdminService $systemService */
        $systemService = app()->make(SystemAdminService::class);
        $admin         = $systemService->get(['username' => $post['username']]);
        if ($admin->isEmpty()) {
            $this->error('用户不存在');
        }
        if (password($post['password']) != $admin->password) {
            $this->error('密码错误');
        }
        if ($admin->status == 0) {
            $this->error('账号已被禁用');
        }
        $admin->login_num += 1;
        $admin->save();
        $admin = $admin->toArray();
        unset($admin['password']);
        $admin['expire_time'] = $post['keep_login'] == 1 ? true : time() + 86400;
        session('admin', $admin);
        $this->success('登录成功');
    }

    /**
     * 用户退出
     */
    public function out()
    {
        session('admin', null);
        $this->success('退出登录成功');
    }

    /**
     * 验证码
     * @return \think\Response
     */
    public function captcha()
    {
        return Captcha::create();
    }
}
